package editor;

import org.fife.ui.rtextarea.RTextScrollPane;

import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.rtf.RTFEditorKit;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

// Here is the main function of the open file function
public class Open {
    public String openitem(String filepathname, String filename){

        File file = new File(filepathname);
        String[] s = filename.split("\\.");
        if (s[1].equals("txt")){  //The most common case is to open a text file
            try {

                FileInputStream in = new FileInputStream(file);
                byte[] byt = new byte[1024];
                int len = in.read(byt);
                in.close();
                return new String(byt, 0, len);

            } catch (IOException fileNotFoundException) {
                fileNotFoundException.printStackTrace();
            }
        }else if (s[1].equals("rtf")){
            // When the opened file is of type "rtf", compatibility processing is carried out
            RTFEditorKit rtfEditorKit = new RTFEditorKit();
            DefaultStyledDocument dsd = new DefaultStyledDocument();

            try {
                rtfEditorKit.read(new FileInputStream(file),dsd, 0);
                String text = new String(dsd.getText(0,dsd.getLength()));
                return text;
            } catch (IOException | BadLocationException e) {
                e.printStackTrace();
            }

        }
        return null;
    }
    public RTextScrollPane opencoloritem(String filepathname, String filename) {
    // When receiving a request to open the source code,
        // it will be compatible with the source code with
        // a new interface and support the highlight function
            Color color = new Color();
            File file = new File(filepathname);
            try {
                color.TextEditorDemo(file);
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }

            return color.rtext;

    }

}
